﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using deviceManage.Models;
using deviceManage.vo;
using deviceManage.Filters;

namespace deviceManage.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary>
    [CheckLoginAttribute]
    public class UserController : Controller
    {
        private readonly DeviceCtx _context;

        public UserController(DeviceCtx context)
        {
            _context = context;
        }

        //列表主页
        public IActionResult Index()
        {
            return View();
        }

        //ajax 获取分页数据
        public AjaxResult List(int page, int limit, User param)
        {

            AjaxResult r = new AjaxResult();
            IQueryable<User> query = _context.User.Where(p => p.Deleted == 0);

            if (!string.IsNullOrWhiteSpace(param.Name))
            {
                query = query.Where(p => p.Name == param.Name);
            }
            if (!string.IsNullOrWhiteSpace(param.Name))
            {
                query = query.Where(p => p.Name == param.Name);
            }
            if (!string.IsNullOrWhiteSpace(param.Cellphone))
            {
                query = query.Where(p => p.Cellphone == param.Cellphone);
            }
            if (!string.IsNullOrWhiteSpace(param.Email))
            {
                query = query.Where(p => p.Email == param.Email);
            }
            if (!string.IsNullOrWhiteSpace(param.LoginName))
            {
                query = query.Where(p => p.LoginName == param.LoginName);
            }
            
            r.Count = query.Count();
            r.Code = 0;
            r.Data = query.Include(p=>p.Depart)
              .Skip((page - 1) * limit).Take(limit)
                .ToList();

            return r;
        }


        /// <summary>
        /// 进入创建页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Create()
        {
            var roleList = this._context.Role.OrderBy(p=>p.RoleName).ToList(); //角色
            var departList = _context.Depart.Where(p => p.Deleted == 0).OrderBy(p => p.SortOrder).ToList(); //部门

            return View(new Tuple<List<Role>, List<Depart>>(roleList, departList));        
        }


        [HttpPost]
        public AjaxResult doCreate( User User,string[] roles)
        {

            var count = _context.User.Where(p => p.LoginName == User.LoginName && p.Deleted == 0).Count();
            if (count > 0)
            {
                return AjaxResult.GetError("登录名已存在，请检查后重新添加");
            }
            User.Deleted = 0;
            _context.Add(User);
            _context.SaveChanges();

            //保存角色
            foreach(string r in roles)
            {
                RoleUser ru = new RoleUser();
                ru.RoleId = r;
                ru.UserId = User.Id;
                this._context.RoleUser.Add(ru);
            }
            this._context.SaveChanges();

            return AjaxResult.GetOK("操作成功！");
        }

        /// <summary>
        /// 进入编辑页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> Edit(string id)
        {
            var roleList = this._context.Role.OrderBy(p => p.RoleName).ToList();
            var User = await _context.User.FindAsync(id);
            var departList = _context.Depart.Where(p => p.Deleted == 0).OrderBy(p => p.SortOrder).ToList(); //部门
            return View(new Tuple<User,List<Role>,List<Depart>>(User,roleList, departList));
        }

        /// <summary>
        /// 提交编辑
        /// </summary>        
        /// <returns></returns>
        [HttpPost]
        public AjaxResult DoEdit(User editUser,string[] roles)
        {
            User User = this._context.User.Single(p => p.Id == editUser.Id);
           
            User.Deleted = 0;
            User.Name = editUser.Name;
         //   User.LoginName = editUser.LoginName;
            User.Pass = editUser.Pass;
            User.DepartId = editUser.DepartId;
            User.Email = editUser.Email;
            User.Cellphone = editUser.Cellphone;
            this._context.SaveChanges(); //保存

            //删除角色
            var authRoleList = this._context.RoleUser.Where(p => p.UserId == User.Id).ToList();
            foreach(var authRole in authRoleList)
            {
                this._context.RoleUser.Remove(authRole);
            }

            //保存角色
            foreach (string r in roles)
            {
                RoleUser ru = new RoleUser();
                ru.RoleId = r;
                ru.UserId = User.Id;
                this._context.RoleUser.Add(ru);
            }
            this._context.SaveChanges();


            return AjaxResult.GetOK("保存成功！");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AjaxResult Delete(string id)
        {
            AjaxResult result = new AjaxResult();
            if (id == null) return AjaxResult.GetError("删除失败！");

            result.Code = 1;
            var User = _context.User.FirstOrDefault(m => m.Id == id);
            if (User == null) return AjaxResult.GetError("未找到数据");

            if (User.LoginName.Equals("admin"))
            {
                return AjaxResult.GetError("不能删除管理员用户");
            }

            User.Deleted = 1;

            //删除角色
            var authRoleList = this._context.RoleUser.Where(p => p.UserId == User.Id).ToList();
            foreach (var authRole in authRoleList)
            {
                this._context.RoleUser.Remove(authRole);
            }

            _context.SaveChanges();
            return AjaxResult.GetOK("删除成功");
        }

        private bool UserExists(string id)
        {
            return _context.User.Any(e => e.Id == id);
        }

        public List<RoleUser> getRoleUser(string id )
        {
            var authRoleList = this._context.RoleUser.Where(p => p.UserId == id).ToList();
            return authRoleList;
        }
    }
}
